
<script setup>
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import request from "@/utils/request.js"

const chatList = ref(null);
const loading = ref(false);

// Props 用于可配置性
const props = defineProps({
  chatId: {
    type: String,
    default: "chat_1759501967000_g4gk0elj6",
  },
  apiBaseUrl: {
    type: String,
    default: "http://localhost:8080",
  },
});

const emit= defineEmits(['message-sent','message-received']);

const data=reactive({
  messages:[
    {role:"USER",content:"你是谁？"},
    {role:"ASSISTANT",content: "你好我是你的智能机器人"},
  ],
  currentMessage:"",
  inputMessage:''
})

const getHistory = async () => {
  try {
    const result = await request.get(`${props.apiBaseUrl}/ai-chat/history`, { chatId: props.chatId });
    data.messages = result.data; // result 是历史消息数组
    console.log('历史记录:', data.messages);
    emit("message-received",data.messages)
  } catch (e) {
    console.error('获取历史记录失败:', e);
  }
};

const sendMessage = async (prompt) => {
  if (!prompt || loading.value) return;  // 防止空消息和重复发送

  loading.value = true;
  data.messages.push({role:"USER", content:prompt});
  data.currentMessage = '';
  data.inputMessage = '';
  emit("message-sent",prompt)
  try {
    const source = request.chatStream(
        `${props.apiBaseUrl}/ai-chat/prompt`,
        {prompt, chatId:props.chatId},
        (text) => {
          if (text === '[DONE]') {
            // 收到结束标志
            data.messages.push({
              role: "ASSISTANT",
              content: data.currentMessage
            });
            data.currentMessage = '';
            loading.value = false;
            emit("message-received", data.messages);
          } else {
            // 累加响应内容
            data.currentMessage += text;
          }
        }
    );

    // 错误处理
    source.onerror = () => {
      loading.value = false;
      source.close();
      console.log('SSE连接已关闭或发生错误');
    };

  } catch (error) {
    console.error('发送消息失败:', error);
    loading.value = false;
  }
};

// 监听消息列表与流式消息变化
watch(
    () => [data.messages.length, data.currentMessage], // 数量和流式消息变化都触发
    () => {
      nextTick(() => {
        if (chatList.value) {
          chatList.value.scrollTop = chatList.value.scrollHeight;
        }
      });
    }
);

onMounted(async ()=>{
  await getHistory()
})

</script>
<template>
  <div class="chat-container">
    <div class="chat-message" ref="chatList">
      <div class="messages" v-for="(message,index) in data.messages" :key="index">
        <div class="history-message" :class="['message',message.role]">
          {{message.content}}
        </div>
      </div>
      <div v-if="data.currentMessage" class="current-message">
        {{data.currentMessage}}
      </div>
    </div>
    <div class="chat-input">
      <input type="text" v-model="data.inputMessage" placeholder="请输入..." @keyup.enter="sendMessage(data.inputMessage)">
      <button @click="sendMessage(data.inputMessage)" :disabled="loading">{{ loading ? '发送中...' : '发送' }}</button>
    </div>
  </div>
</template>


